begin
  require File.dirname(__FILE__) + '/test_helper'
rescue LoadError
  require 'test/unit'
end
require 'fileutils'

# Must set before requiring generator libs.
TMP_ROOT = File.dirname(__FILE__) + "/tmp" unless defined?(TMP_ROOT)
PROJECT_NAME = "myproject" unless defined?(PROJECT_NAME)
app_root = File.join(TMP_ROOT, PROJECT_NAME)
if defined?(APP_ROOT)
  APP_ROOT.replace(app_root)
else
  APP_ROOT = app_root
end
if defined?(RAILS_ROOT)
  RAILS_ROOT.replace(app_root)
else
  RAILS_ROOT = app_root
end

begin
  require 'rubigen'
rescue LoadError
  require 'rubygems'
  require 'rubigen'
end
require 'rubigen/helpers/generator_test_helper'

module RubiGen::GeneratorTestHelper
  def assert_file_contains(keyword, filename)
    ipr = IO.readlines(File.join(APP_ROOT, filename)).to_s
    assert(ipr =~ Regexp.new(keyword))
  end

  def run_generated_build_script(cmd)
    FileUtils::cd(APP_ROOT) do
      puts "Running generated build script in #{FileUtils::pwd} with #{cmd}"
      `#{cmd}`
      raise "Exit code #{$?} while running generated build script with #{cmd}" if ($?.to_s != "0")
    end
  end

  def run_generated_cleaner(cmd)
    FileUtils::cd(APP_ROOT + '/script') do
      puts "Running generated clean script in #{FileUtils::pwd} with #{cmd}"
      `#{cmd}`
      raise "Exit code #{$?} while running generated build script with #{cmd}" if ($?.to_s != "0")
    end
  end
  
  def sources
    [ RubiGen::PathSource.new(:test, File.join(File.dirname(__FILE__), "..", "app_generators")),
      RubiGen::PathSource.new(:test, File.join(File.dirname(__FILE__), "..", "cleaner_generators"))]
  end

  # Some generator-related assertions:
  #   assert_generated_file(name, &block) # block passed the file contents
  #   assert_directory_exists(name)
  #   assert_generated_class(name, &block)
  #   assert_generated_module(name, &block)
  #   assert_generated_test_for(name, &block)
  # The assert_generated_(class|module|test_for) &block is passed the body of the class/module within the file
  #   assert_has_method(body, *methods) # check that the body has a list of methods (methods with parentheses not supported yet)
  #
  # Other helper methods are:
  #   app_root_files - put this in teardown to show files generated by the test method (e.g. p app_root_files)
  #   bare_setup - place this in setup method to create the APP_ROOT folder for each test
  #   bare_teardown - place this in teardown method to destroy the TMP_ROOT or APP_ROOT folder after each test
end

